/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package GUI;

import GUI.CapNhat.CapNhatPhong;
import GUI.Them.ThemPhong;
import BUS.PhongBUS;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.Vector;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author PC
 */
public class PhongGUI extends javax.swing.JPanel {

    /**
     * Creates new form PhongGUI
     */
    public PhongGUI() {
        initComponents();
        LoadForm();
    }
public void LoadForm() {
        try {

            ResultSet rs = PhongBUS.TimKiemTatCa();
            Vector<String> colName = new Vector<>();
            ResultSetMetaData data = rs.getMetaData();
            int count = data.getColumnCount();
            colName.add("Số Hiệu");
            colName.add("Toa");
            
           
            Vector row;
            DefaultTableModel dtm = new DefaultTableModel() {
                @Override
                public boolean isCellEditable(int i, int i1) {
                    return false;
                }
            };
            dtm.setColumnIdentifiers(colName);
            while (rs.next()) {
                row = new Vector();
                for (int i = 1; i <= count; i++) {
                    row.add(rs.getString(i));
                }
                dtm.addRow(row);
            }
            jTable1.setModel(dtm);
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
}
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel3 = new javax.swing.JPanel();
        jButtonThem = new javax.swing.JButton();
        jButtonXoa1 = new javax.swing.JButton();
        jButtonCapNhat = new javax.swing.JButton();
        jButtonXuat = new javax.swing.JButton();
        jButtonIn = new javax.swing.JButton();
        cbbxuatra = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtnoiluufile = new javax.swing.JTextField();
        btnchooser = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();

        jPanel1.setForeground(new java.awt.Color(0, 51, 255));

        jTable1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(51, 255, 51)));
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jPanel3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 51, 204)));
        jPanel3.setForeground(new java.awt.Color(51, 51, 51));

        jButtonThem.setForeground(new java.awt.Color(255, 0, 51));
        jButtonThem.setText("Thêm");
        jButtonThem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonThemActionPerformed(evt);
            }
        });

        jButtonXoa1.setForeground(new java.awt.Color(255, 0, 102));
        jButtonXoa1.setText("Xóa");
        jButtonXoa1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonXoa1ActionPerformed(evt);
            }
        });

        jButtonCapNhat.setForeground(new java.awt.Color(255, 0, 0));
        jButtonCapNhat.setText("Cập Nhật");
        jButtonCapNhat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCapNhatActionPerformed(evt);
            }
        });

        jButtonXuat.setForeground(new java.awt.Color(255, 51, 51));
        jButtonXuat.setText("Xuất");
        jButtonXuat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonXuatActionPerformed(evt);
            }
        });

        jButtonIn.setForeground(new java.awt.Color(255, 0, 0));
        jButtonIn.setText("In");

        cbbxuatra.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Microsoft Excel", "Microsoft Word" }));
        cbbxuatra.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbbxuatraActionPerformed(evt);
            }
        });

        jLabel4.setText("Nơi Lưu File:");

        jLabel3.setText("Xuất Ra:");

        txtnoiluufile.setText("C:\\\\DanhSachPhong.xls");
        txtnoiluufile.setEnabled(false);
        txtnoiluufile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtnoiluufileActionPerformed(evt);
            }
        });

        btnchooser.setText("...");
        btnchooser.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnchooserActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addComponent(jButtonThem, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButtonXoa1, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(29, 29, 29)
                .addComponent(jButtonCapNhat, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(cbbxuatra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(txtnoiluufile, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnchooser, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButtonXuat, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButtonIn, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButtonXuat, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButtonIn, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButtonThem, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButtonXoa1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButtonCapNhat, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(cbbxuatra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel4)
                            .addComponent(txtnoiluufile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnchooser))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 344, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        jPanel2.setBackground(new java.awt.Color(0, 51, 255));

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(255, 0, 51));
        jLabel1.setText("From Phòng Tàu ");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(196, 196, 196)
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(393, 393, 393))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLabel1)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(1, 1, 1)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonCapNhatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCapNhatActionPerformed
         int index = jTable1.getSelectedRow();
        if (index < 0) {
            JOptionPane.showMessageDialog(this, "Chưa chọn dòng cần cập nhật");
            return;
        }
        String maNV = jTable1.getValueAt(index, 0).toString();

        CapNhatPhong CapNhatnv = new CapNhatPhong(this, maNV);
        CapNhatnv.setVisible(true);
    }//GEN-LAST:event_jButtonCapNhatActionPerformed

    private void jButtonXoa1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonXoa1ActionPerformed
      try {
            int index = jTable1.getSelectedRow();

            if (index < 0) {
                JOptionPane.showMessageDialog(this, "Chưa chọn dòng cần xóa");
                return;
            }
            String MaNV = String.valueOf( jTable1.getValueAt(index, 0));
             if (JOptionPane.showConfirmDialog(this, "Bạn có muốn xóa Phòng này ?", "Xác nhận xóa", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.OK_OPTION) {
            if ( PhongBUS.Xoa(MaNV) ) {
                JOptionPane.showMessageDialog(this, "Xóa Phòng thành công");
                LoadForm();
            } else {
                JOptionPane.showMessageDialog(this, "Xóa Phòng thát bại");
            }}
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getStackTrace(), "Thông báo lỗi", JOptionPane.OK_OPTION);

        }
    }//GEN-LAST:event_jButtonXoa1ActionPerformed

    private void jButtonThemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonThemActionPerformed
          ThemPhong tnv = new ThemPhong(this);
        tnv.setVisible(true);
    }//GEN-LAST:event_jButtonThemActionPerformed

    private void cbbxuatraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbbxuatraActionPerformed
        try {
            txtnoiluufile.setText(removeDuoi(txtnoiluufile.getText()) + "." + GetDuoi());
        } catch (Exception e) {
        }
    }//GEN-LAST:event_cbbxuatraActionPerformed
 private String GetDuoi() {
        if (cbbxuatra.getSelectedIndex() == 0) {
            return "xls";
        }
        return "doc";
    }

    private String removeDuoi(String Duoi) {
        Duoi = Duoi.replace(".xls", "");
        Duoi = Duoi.replace(".doc", "");
        return Duoi;
    }
    private void txtnoiluufileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtnoiluufileActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtnoiluufileActionPerformed

    private void btnchooserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnchooserActionPerformed
        JFileChooser fc = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter(cbbxuatra.getSelectedItem().toString(), GetDuoi());
        fc.setFileFilter(filter);
        fc.setSelectedFile(new File(txtnoiluufile.getText()));
        int returnVal = fc.showSaveDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            txtnoiluufile.setText(file.getPath());
        }
    }//GEN-LAST:event_btnchooserActionPerformed

    private void jButtonXuatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonXuatActionPerformed
        // TODO add your handling code here:
          if (jTable1.getRowCount() == 0) {
            JOptionPane.showMessageDialog(null, "Không Có Dữ Liệu");
        } else {
            XuatDanhSachPhong();
        }
    }//GEN-LAST:event_jButtonXuatActionPerformed
  private void XuatDanhSachPhong() {
        try {
            byte[] bom = new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF};
            FileOutputStream fout = new FileOutputStream(txtnoiluufile.getText().trim());
            fout.write(bom);
            OutputStreamWriter bw = new OutputStreamWriter(fout, "UTF-8");
            PrintWriter printWriter = new PrintWriter(bw);
            printWriter.print("\n");
            printWriter.print(getHTML());
            bw.close();
            int result = JOptionPane.showConfirmDialog(null, "Xuất Danh Sách Phòng Thành Công.\nBạn Có Muốn Mở File Vừa Xuất?", "Thông Báo", JOptionPane.YES_NO_OPTION);
            if (result == JOptionPane.YES_OPTION) {
                Runtime runtime = Runtime.getRuntime();
                Process process = runtime.exec("cmd /c start " + txtnoiluufile.getText().trim());
            }
        } catch (Exception e) {
            if (e.getMessage().indexOf("(Access is denied)") != -1) {
                JOptionPane.showMessageDialog(null, "Không thể lưu dữ liệu vào Ổ Đĩa " + txtnoiluufile.getText().substring(0, 1) + ". Vui lòng chọn ổ khác");
            } else {
                JOptionPane.showMessageDialog(null, e.getMessage());
            }
        }

    }

    private String getHTML() {
        StringBuilder sb = new StringBuilder();
        sb.append(getHeader());
        sb.append("<caption><center><h2><br><b>" + "Danh Sách Nhân Viên" + "</b><br></h2></center></caption>");
        sb.append("<tr>");
        sb.append("<th>Số Hiệu</th>");
        sb.append("<th>Toa</th>");
        sb.append("</tr>");
        for (int i = 0; i < jTable1.getRowCount(); i++) {
            sb.append("<tr>");
            for (int j = 0; j < 2; j++) {
                sb.append("<td>" + jTable1.getValueAt(i, j).toString() + "</td>");
            }
            sb.append("</tr>");
        }
        sb.append(getFooter());
        return sb.toString();
    }

    private String getHeader() {
        if (cbbxuatra.getSelectedIndex() == 1) {
            return "<html><meta charset='utf-8' /><style>table tr td,table th{border:1px solid #000;padding:3px}table{margin-top:30px}</style>"
                    + "<div style='width:100%;text-align:center'>"
                    + "<div style='width'900px;margin:0px auto;text-align:left;padding:10px'>"
                    + "<table width='900' cellspacing='0' cellpadding='0'>";
        } else {
            return "<html><meta charset='utf-8' /><table border='1' style='font-family:tahoma' cellpadding='3'>";
        }
    }

    private String getFooter() {
        if (cbbxuatra.getSelectedIndex() == 1) {
            return "</table></div></div></html>";
        } else {
            return "</table></html>";
        }
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnchooser;
    private javax.swing.JComboBox cbbxuatra;
    private javax.swing.JButton jButtonCapNhat;
    private javax.swing.JButton jButtonIn;
    private javax.swing.JButton jButtonThem;
    private javax.swing.JButton jButtonXoa1;
    private javax.swing.JButton jButtonXuat;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField txtnoiluufile;
    // End of variables declaration//GEN-END:variables
}
